package com.cyan.netty.c1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class HelloServer {
    public static void main(String[] args) {
        // ServerBootstrap：启动器，负责组装netty组件
        new ServerBootstrap()
                // eventLoop
                .group(new NioEventLoopGroup())
                // 选择服务器的 ServerSocketChannel 实现
                .channel(NioServerSocketChannel.class)
                // boss负责处理连接，worker(child)负责处理读写
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    // channel代表和客户端进行数据读写的通道，Initializer 初始化
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 添加具体的Handler
                        ch.pipeline().addLast(new StringDecoder()); // 将 ByteBuf 转换成字符串
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { // 自定义 Handler
                            @Override // 读事件
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                System.out.println("msg: " + msg);
                            }
                        });
                    }
                }).bind(8080); // 监听端口
    }
}
